/**
 * 个人信息页面
 * @returns
 */
import { useCallback, useEffect, useState } from 'react';
import { Card, Avatar, Button, List, Modal, Form, Input, message, Popconfirm } from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  PhoneOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';
import useUserInfoStore from '@/store/userInfoStore';
import {
  addAddressApi,
  deleteAddressApi,
  getAddressListApi,
  getUserInfoApi,
  updateAddressApi,
  updateUserInfoApi,
} from '@/api/user';

const Profile = () => {
  const userInfo = useUserInfoStore((state) => state.userInfo);
  const setUserInfo = useUserInfoStore((state) => state.setUserInfo);
  // 地址弹窗
  const [isAddressModalVisible, setIsAddressModalVisible] = useState(false);
  // 地址表单
  const [form] = Form.useForm();
  // 编辑地址
  const [editingAddress, setEditingAddress] = useState<Address | null>(null);
  // 编辑资料弹窗
  const [isEditProfileModalVisible, setIsEditProfileModalVisible] = useState(false);
  // 编辑资料表单
  const [formEditProfile] = Form.useForm();

  // 模拟地址数据
  const [addresses, setAddresses] = useState<Address[]>([]);

  // 获取地址列表
  const getAddressList = useCallback(() => {
    getAddressListApi(Number(userInfo.id)).then((res) => {
      setAddresses(res.data);
    });
  }, [userInfo.id]);

  useEffect(() => {
    getAddressList();
  }, [getAddressList, userInfo.id]);

  // 新增地址
  const handleAddAddress = () => {
    setEditingAddress(null);
    form.resetFields();
    setIsAddressModalVisible(true);
  };

  // 编辑地址
  const handleEditAddress = (address: Address) => {
    setEditingAddress(address);
    form.setFieldsValue(address);
    setIsAddressModalVisible(true);
  };

  // 删除地址
  const handleDeleteAddress = (id: number) => {
    deleteAddressApi(id).then(() => {
      message.success('删除成功');
      getAddressList();
    });
  };

  // 提交地址
  const handleAddressSubmit = () => {
    form.validateFields().then((values) => {
      if (editingAddress) {
        // 编辑地址
        updateAddressApi({
          ...editingAddress,
          harvest: values.harvest,
          harvest_address: values.harvest_address,
        }).then(() => {
          message.success('修改成功');
          setIsAddressModalVisible(false);
          getAddressList();
        });
      } else {
        addAddressApi({
          user_id: Number(userInfo.id),
          harvest: values.harvest,
          harvest_address: values.harvest_address,
        }).then(() => {
          message.success('添加成功');
          setIsAddressModalVisible(false);
          getAddressList();
        });
      }
    });
  };

  // 编辑资料
  const handleEditProfile = () => {
    setIsEditProfileModalVisible(true);
    formEditProfile.setFieldsValue({
      user_name: userInfo.user_name,
      phone: userInfo.phone,
    });
  };

  // 提交编辑资料
  const handleEditProfileSubmit = () => {
    formEditProfile.validateFields().then((values) => {
      updateUserInfoApi({
        id: Number(userInfo.id),
        user_name: values.user_name,
        phone: values.phone,
      }).then(() => {
        message.success('修改成功');
        setIsEditProfileModalVisible(false);
        // 更新用户信息
        getUserInfoApi().then((res) => {
          setUserInfo(res.data);
          localStorage.setItem('userInfo', JSON.stringify(res.data));
        });
      });
    });
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4">
      <div className="max-w-4xl mx-auto">
        {/* 用户信息卡片 */}
        <Card
          style={{ marginBottom: '20px' }}
          className="shadow-md"
        >
          <div className="flex items-center space-x-6">
            <Avatar
              size={100}
              src={'https://api.dicebear.com/7.x/avataaars/svg?seed=Felix'}
              className="border-4 border-emerald-100"
            />
            <div className="flex-1">
              <h2 className="text-2xl font-bold text-gray-800 mb-2">{userInfo.user_name}</h2>
              <div className="flex items-center text-gray-600">
                <PhoneOutlined className="mr-2" />
                <span>{userInfo.phone}</span>
              </div>
            </div>
            <Button
              type="primary"
              className="bg-emerald-600 hover:bg-emerald-700 border-none"
              onClick={handleEditProfile}
            >
              编辑资料
            </Button>
          </div>
        </Card>

        {/* 地址管理 */}
        <Card
          title={
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <EnvironmentOutlined className="text-emerald-600 mr-2" />
                <span className="text-lg font-semibold">收货地址</span>
              </div>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddAddress}
                className="bg-emerald-600 hover:bg-emerald-700 border-none"
              >
                新增地址
              </Button>
            </div>
          }
          className="shadow-md"
        >
          <List
            dataSource={addresses}
            renderItem={(address) => (
              <List.Item
                actions={[
                  <Button
                    key="edit"
                    type="link"
                    icon={<EditOutlined />}
                    onClick={() => handleEditAddress(address)}
                  >
                    编辑
                  </Button>,
                  <Popconfirm
                    key="delete"
                    title="确定要删除这个地址吗？"
                    onConfirm={() => handleDeleteAddress(address.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button
                      type="link"
                      danger
                      icon={<DeleteOutlined />}
                    >
                      删除
                    </Button>
                  </Popconfirm>,
                ]}
              >
                <List.Item.Meta
                  title={
                    <div className="flex items-center">
                      <span className="font-medium">{address.harvest}</span>
                    </div>
                  }
                  description={`${address.harvest_address}`}
                />
              </List.Item>
            )}
          />
        </Card>
      </div>

      {/* 地址编辑弹窗 */}
      <Modal
        title={editingAddress ? '编辑地址' : '新增地址'}
        open={isAddressModalVisible}
        onOk={handleAddressSubmit}
        onCancel={() => setIsAddressModalVisible(false)}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="harvest"
            label="收货人"
            rules={[{ required: true, message: '请输入收货人姓名' }]}
          >
            <Input placeholder="请输入收货人姓名" />
          </Form.Item>
          <Form.Item
            name="harvest_address"
            label="详细地址"
            rules={[{ required: true, message: '请输入详细地址' }]}
          >
            <Input.TextArea
              placeholder="请输入详细地址"
              rows={3}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑资料弹窗 */}
      <Modal
        title="编辑资料"
        open={isEditProfileModalVisible}
        onOk={handleEditProfileSubmit}
        onCancel={() => {
          setIsEditProfileModalVisible(false);
          formEditProfile.resetFields();
        }}
      >
        <Form
          form={formEditProfile}
          layout="vertical"
        >
          <Form.Item
            rules={[{ required: true, message: '请输入昵称' }]}
            name="user_name"
            label="昵称"
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>
          <Form.Item
            rules={[{ required: true, message: '请输入手机号' }]}
            name="phone"
            label="手机号"
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Profile;
